<script setup lang="ts">
import { onBeforeUnmount, ref, shallowRef } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";
import type { IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import { DomEditor } from "@wangeditor/editor";
import { nextTick } from "vue";
import { UPLOAD_IMAGE_URL } from "@/api/images";
import { ImageItem } from "types/image";

const SERVER_URL = import.meta.env.VITE_SERVER_URL;

const modelValue = defineModel<string>({ default: "" });

defineOptions({
  name: "RichTextEditor"
});

const mode = "default";
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("");
const toolbarConfig: Partial<IToolbarConfig> = {
  excludeKeys: ["fullScreen", "group-video"]
};

const editorConfig: Partial<IEditorConfig> = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      // 服务端上传地址，根据实际业务改写
      server: UPLOAD_IMAGE_URL,
      // form-data 的 fieldName，根据实际业务改写
      fieldName: "file",
      // 选择文件时的类型限制，根据实际业务改写
      allowedFileTypes: ["image/png", "image/jpg", "image/jpeg"],
      // 自定义插入图片
      customInsert(res: ImageItem, insertFn) {
        // res.data.url是后端返回的图片地址，根据实际业务改写
        console.log(res);
        insertFn(
          `${SERVER_URL}/static/images/${res.folder}/${res.hash}.${res.format}`
        );
        // if (res.data.url) {
        //   setTimeout(() => {
        //     // insertFn插入图片进编辑器
        //     insertFn(SERVER_URL + res.data.url);
        //   }, 2000);
        // }
      }
    }
  }
};

const handleCreated = editor => {
  // 记录 editor 实例，重要！
  editorRef.value = editor;
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleChange = editor => {
  console.log(editor.getHtml());
  // modelValue.value = editor.getHtml();
};
</script>

<template>
  <div class="wangeditor">
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      style="border-bottom: 1px solid #ccc"
    />
    <Editor
      v-model="modelValue"
      :defaultConfig="editorConfig"
      :mode="mode"
      style="height: 500px; overflow-y: hidden"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>
<style scoped lang="scss">
.wangeditor {
  border: 1px solid #ccc;
  overflow: hidden;
}
</style>
